﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapMgr : MonoBehaviour
{
    public static MapMgr Instance;

    static float outerRadius = HexMetrics.outerRadius;
    static float innerRadius = HexMetrics.innerRadius;

    Dictionary<int, GameObject> _gridIndex2Item = new Dictionary<int, GameObject>();
    Tuple<int, int> _hexGrid;
    List<MapItem> _mapItemList;
    Dictionary<int, MapItem> _gridIndex2MapItem;

    private void Awake()
    {
        Instance = this;
    }

    Color _obstacleColor;
    Color _normalColor;
    // Use this for initialization
    void Start()
    {
        //生成数据层
        _mapItemList = new List<MapItem>();
        _gridIndex2MapItem = new Dictionary<int, MapItem>();
        for (int i = 0; i < UtilGeometry.MapHorizonLen; i++)
        {
            for (int j = 0; j < UtilGeometry.MapVerticalLen; j++)
            {

                var item = new MapItem();
                item.x = i;
                item.y = j;
                item.isObstacle = UnityEngine.Random.Range(0f, 1f) < 0.2f;
                _mapItemList.Add(item);
                _gridIndex2MapItem.Add(UtilGeometry.GetGridIndex(i, j), item);
            }
        }

        _obstacleColor = new Color(123f/255f, 49f/255f, 49f/255f);
        _normalColor = new Color(64f / 255f, 133f / 255f, 64f / 255f);
        //生成表现
        var cityMgr = CityMgr.Instance;
        foreach (var mapItem in _mapItemList)
        {
            Vector3 pos = HexMetrics.GetPosFromHexGrid(mapItem.x, mapItem.y);
            GameObject Plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
            Plane.name = "Hex_" + mapItem.x + "_" + mapItem.y;
            Plane.AddComponent<HexCell>();
            Plane.transform.position = pos;
            var render = Plane.GetComponent<MeshRenderer>();
            render.material.color = mapItem.isObstacle ? _obstacleColor : _normalColor;// new Color(i / col, (i + j) / (col + row), j / row);
            if (mapItem.isObstacle)
            {
                var city = Plane.AddComponent<City>();
                cityMgr.AddCity(city);
            }
            _gridIndex2Item[UtilGeometry.GetGridIndex(mapItem.x, mapItem.y)] = Plane;
        }

        //初始化地面
        InitFloor();
 
    }

    public float Horizon;
    public float Vertical;
    //初始化地面Boxcollider,让EasyTouchs识别拖动事件（以后可以找个插件，不依赖生成生成Boxcollider）
    private void InitFloor()
    {
        var bc = GetComponent<BoxCollider>();
        Horizon = (HexMetrics.innerRadius * 2 + 0.5f) * UtilGeometry.MapHorizonLen;//Horizon Len
        Vertical = (HexMetrics.innerRadius / 2 + HexMetrics.outerRadius + 1f) * UtilGeometry.MapVerticalLen;//Vertical Len
        bc.size = new Vector3(Horizon, 0.1f, Vertical);
        bc.center = new Vector3(Horizon / 2, 0, Vertical / 2);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="x">HexGridX</param>
    /// <param name="y">HexGridY</param>
    /// <returns></returns>
    private GameObject GetItem(int x, int y)
    {
        var gridIndex = UtilGeometry.GetGridIndex(x, y);
        GameObject gameObject;
        _gridIndex2Item.TryGetValue(gridIndex, out gameObject);
        return gameObject;
    }

    public MapItem GetMapItem(int x, int y)
    {
        MapItem mapItem;
        var gridIndex = UtilGeometry.GetGridIndex(x, y);
        if (!_gridIndex2MapItem.TryGetValue(gridIndex, out mapItem))
            Debug.LogError("Can not find map item:" + x + "," + y);
        return mapItem;
    }

    public List<MapItem> GetMapItemList()
    {
        return _mapItemList;
    }

    /// <param name="x">HexGridX</param>
    /// <param name="y">HexGridY</param>
    public void Click(int x, int y)
    {
        //foreach (var item in _hexGrid2Item.Values)
        //{
        //    item.material.color = Color.green;
        //}
        var item = GetItem(x, y);
        if (item == null)
        {
            return;
        }
        //render.material.color = Color.red;
        StartCoroutine(CoScaleClick(item));
    }

    //点击缩放效果
    IEnumerator CoScaleClick(GameObject item)
    {
        float time = 0.2f;
        var scale = item.transform.localScale;
        var targetScale = new Vector3(HexCell.ScaleSize, HexCell.ScaleSize, HexCell.ScaleSize);
        for (float i = 0; i < time; i += Time.deltaTime)
        {
            item.transform.localScale = Vector3.MoveTowards(scale, targetScale, i / time);
            yield return null;
        }
        scale = item.transform.localScale;
        targetScale = new Vector3(HexCell.Size, HexCell.Size, HexCell.Size);
        for (float i = 0; i < time; i += Time.deltaTime)
        {
            item.transform.localScale = Vector3.MoveTowards(scale, targetScale, i / time);
            yield return null;
        }
    }
}